/*
* shrimp7 JS
* Copyright 2009 Rens Sparrius
*
* http://www.soepgarnaal.com/shrimp7/
* http://shrimp7.googlecode.com/
*
* Licensed under the BSD license.
*/

shrimp7.twitter = shrimp7.fn.twitter = {
	timer: {
		"fetchTimeline":NULL,
		"fetchReplies":NULL,
		"search":{},
		"spy":{}
	},
	me:NULL,
	data:{
		savedSearches:[],
		followers:[],
		directMessages:{
			send:[],
			received:[]
		},
		timeline:[],
		replies:[],
		spy:{
			users:{},
			data:[]
		}
	},
	updatesPerHour:NULL,
	timelineActiveStartId:0,
	setupParams:{
		fetchTimeline:			TRUE,
		fetchReplies:			TRUE,
		fetchSpyUsers:			TRUE,
		fetchSavedSearches:		TRUE,
		tweet:{
			entry:					'<div id="tweet{dataId}-{dataUserId}-{dataI}"class="{cssClass}">'+
										'<img class="tweetImage"src="{dataUserProfileImgUrl}"/>'+
										'<span id="message{dataId}-{dataUserId}">{dataMessage}</span>'+
										'<div style="clear:both;"></div>'+
										'<div class="tweetFooter">'+
											'<div class="tweetInfo">'+
												'{userLink}'+
												'<br/><span>{dataPostTime}</span>'+
											'</div>'+
											'<div class="tweetOptions">'+
												'{tweetRemoveButton}'+
												'{tweetCopyToFacebookButton}'+
												'{tweetReplyButton}'+
												'{tweetCompressed}'+
												'{tweetUserFilter}'+
											'</div>'+
											'<div style="clear:both;"></div>'+
										'</div>'+
									'</div>',
			remove:					'<a href="javascript:(function(){var c = confirm(\'Are you sure you want to delete this tweet?\');if(c){shrimp7.twitter.deleteTweet({id:{dataId},success:function(data){alert(\'Deleted..\');},error:function(){alert(\'Oops, error while deleting.\');}});}})();">'+
										'<img class="tweetOptionDeleteImage"onmouseout="className=\'tweetOptionDeleteImage\'"onmouseover="className=\'tweetOptionDeleteImageHover\'"src="images/icons/trash.png"/>'+
									'</a>',
			reply:					'<a href="javascript:shrimp7.toggleScreen({id:\'statusUpdate\',type:\'dialog\',title:\'Reply\',init:function(){shrimp7.statusUpdate.replyTo={screenname:\'{dataUserScreenname}\',statusId:{dataId}};shrimp7.statusUpdate.starter(null);},returnSelf:false});">'+
										'<img src="images/icons/reply.png"style="width:13px;"/>'+
									'</a>',
			userFilter:				'<a href="javascript:shrimp7.twitter.addFilter({dataUserId});">'+
										'<img src="images/icons/close.png"style="width:13px;"/>'+
									'</a>',
			copyToFacebook:			'<a href="javascript:shrimp7.twitter.copyTweetToFacebook({i},\'normal\')">'+
										'<img class="twitterCopy2FacebookImage"src="images/icons/facebook.png"/>'+
									'</a>',
			spyUser:				'<div class="spyUserRow">'+
										'<div class="spyUserRemove"><img onclick="shrimp7.twitter.removeSpyUser({i})"src="images/icons/close.png"style="width:16px;cursor:pointer;"/></div>'+
										'<div class="spyUsername">{dataUserName}</div>'+
										'<div id="slider{dataUserName}"class="spyUserSlider"></div>'+
										'<div id="slider{dataUserName}value"class="spyUserSliderValue">{dataValue}</div>'+
									'</div>'
		}
	},
	setup:function(obj){
		for(var key in obj){
			this.setupParams[key] = obj[key];
		}
		return window.shrimp7;
	},
	init:function(refreshData){
		if(setting("twitterRefreshTimeline")===""){
			setting("twitterRefreshTimeline",60);
			setting("twitterRefreshReplies",30);
			setting("twitterRefreshDirectMessages",10);
		}else{
			shrimp7.twitter.updatesPerHour = 4+parseInt(setting("twitterRefreshTimeline"),10)+parseInt(setting("twitterRefreshReplies"),10)+parseInt(setting("twitterRefreshDirectMessages"),10);
		}
		
		if(setting("twitterOauthToken")===""){
			$("#twitterSetup").show();
		}else{
			if(setting("twitterOauthTokenAccess")===""){
				$("#twitterSetup").show();
				this.con.requestToken(function(link){
					$("#twitterAuthorizeLogin").html('<a href="'+link+'">Login</a>');
				});
				loading('twitter',FALSE,'full');
			}
			else{
				$("#twitterSetup").hide();
				loading("twitter",TRUE,'full');
				this.start(refreshData);
			}
		}
		return window.shrimp7;
	},
	start:function(refreshData){
		var THIS = shrimp7.twitter;
		if(refreshData){
			// This function use 1 refresh rate
			THIS.con.getUserInfo(setting("twitterUserId"),'document',function(data){
				shrimp7.twitter.me = data;
			});
			
			// This function will use refresh rates
			if(THIS.setupParams.fetchSpyUsers){
				THIS.fetchSpyUsers(FALSE);
			}
			
			if(THIS.setupParams.fetchSavedSearches){
				THIS.fetchSavedSearches({refresh:TRUE});
			}
		}
		
		if(THIS.setupParams.fetchTimeline){
			THIS.fetchTimeline({refresh:refreshData});
		}
		
		if(THIS.setupParams.fetchReplies){
			THIS.fetchReplies(refreshData);
		}
		
		THIS.getReceivedDirectMessages(function(data){
			shrimp7.twitter.data.directMessages.received = data;
		});
		
		if(THIS.data.followers.length===0){
			THIS.con.getFollowersInfo(NULL,'document',function(data){
				shrimp7.twitter.data.followers = data;
			});
		}
		
		return window.shrimp7;
	},
	fetchTimeline:function(obj){
		var THIS = this;
		
		if(obj.refresh||this.data.timeline===NULL){
			// Clear the timer
			clearTimeout(this.timer.fetchTimeline);
			
			var	myDate = new Date(),
				i;
			
			if(setting("twitterUserId")!==""){
				// Try to get the first 4 pages... (because we limit on 15 tweets..)
				this.con.friendsTimeline({limit:90,page:1,callback:function(data){
						
						// Start new timer for fetchTimeline
						THIS.timer.fetchTimeline = setTimeout(function(){
							shrimp7.twitter.fetchTimeline({refresh:TRUE});
						}, 3600000 / parseInt(setting("twitterRefreshTimeline"),10));
						
						// On error, wait 1 cycle, and try again..
						if(data===errorTxt){
							// Run the success callback
							if(obj.error!==UNDEFINED){
								obj.error(data);
							}
						}
						// If NO error just do the job..
						else{
							THIS.normalizer(data,function(newData){
								data = newData;
							});
							if(data[0]!==UNDEFINED){
								for(var key in THIS.data.spy){
									data = data.concat(THIS.data.spy[key]);
								}
								
								data = data.sort(sortById);
								THIS.data.timeline = data;
								
								// Fill the shrimp7.twitter.firstStart variable, so other procedures can see twitter was
								// already running or running for the first time..
								THIS.firstStart = 1;
								
								// Run the success callback
								if(obj.success!==UNDEFINED){
									obj.success(data);
								}
							}
						}
					}
				});
			}
			// Run the success callback
			else if(obj.error!==UNDEFINED){
				obj.error('No userId');
			}
		}
		return window.shrimp7;
	},
	fetchReplies:function(obj){
		var THIS = this;
		if(obj.refresh){
			clearTimeout(this.timer.fetchReplies);
			
			this.con.repliesTimeline(100,1,function(data){
				
				THIS.timer.fetchReplies = setTimeout(function(data){
					shrimp7.twitter.fetchReplies(TRUE);
				},3600000/parseInt(setting("twitterRefreshReplies"),10));
				
				if(data!==errorTxt){
					THIS.normalizer(data,function(newData){
						data = newData;
					});
					
					// cache the data..
					THIS.data.replies = data;
					
					// Run the success callback
					if(obj.success!==UNDEFINED){
						obj.success(data);
					}
				}else if(obj.error!==UNDEFINED){
					obj.error(data);
				}
			});
		}else{
			if(obj.success!==UNDEFINED)
				obj.success(this.data.replies);
		}
		return window.shrimp7;
	},
	/*
	* shrimp7.twitter.refreshTimelineData(object)
	*
	* This function can handle statuses data from the Twitter servers, for example:
	* friendstimeline, mentions etc..
	*
	* Required:
	*
	* data				OBJECT
	* dropIn			STRING
	* 
	* Optional:
	*
	* startId			INTEGER
	* saveStartIdent	STRING
	* totalPerPage		INTEGER
	* dom				STRING
	* pagingPrefix		STRING (soon)
	*
	*/
	refreshTimelineData:function(obj){
		var	dom = NULL,
			filters = String(setting("twitterStreamFilters")),
			i,
			dataUpdate=[],
			pagingValues,
			htmlStr = '';
		
		if(obj.dom!==UNDEFINED){
			dom = obj.dom;
		}
		
		// When there is no data (yet)..
		if(obj.data===NULL){
			$(obj.dropIn,dom).html("No data yet, please try again later..");
			return TRUE;
		}
		
		// Set default values for optional parameters
		if(obj.startId===UNDEFINED){
			obj.startId = 0;
		}
		if(obj.totalPerPage===UNDEFINED){
			obj.totalPerPage = 10;
		}
		
		// Save startId, this works with an identifier. For example: timeline, replies..
		if(obj.saveStartIdent!==UNDEFINED){
			if(this.timelineActiveStartId[obj.saveStartIdent]!==UNDEFINED){
				obj.startId = this.timelineActiveStartId[obj.saveStartIdent];
			}
			this.timelineActiveStartId[obj.saveStartIdent] = obj.startId;
		}
		
		/*
		* Twitter user filter..
		*/
		
		if(obj.data!==FALSE){
			for(i=0;i<obj.data.length;i++){
				if(filters.match(obj.data[i].userId)===NULL){
					dataUpdate.push(obj.data[i]);
				}
			}
		}
		
		pagingValues = paging(dataUpdate.length,obj.totalPerPage,obj.startId);
		
		for(i=obj.startId;i<pagingValues.endId;i++){
			htmlStr=htmlStr+shrimp7.twitter.buildTweet(dataUpdate[i],i);
		}
		
		if(pagingValues.nextStart!==NULL){
			$(obj.pagingPrefix+'Next').show().unbind('click').click(function(){
				shrimp7.twitter.refreshTimelineData({
					startId:		pagingValues.nextStart,
					totalPerPage:	obj.totalPerPage,
					dropIn:			obj.dropIn,
					dom:			dom,
					data:			obj.data,
					pagingPrefix:	obj.pagingPrefix
				});
			});
		}else{
			$(obj.pagingPrefix+'Next').unbind('click').hide();
		}
		if(obj.startId>0){
			$(obj.pagingPrefix+'Previous').show().unbind('click').click(function(){
				shrimp7.twitter.refreshTimelineData({
					startId:		pagingValues.previousStart,
					totalPerPage:	obj.totalPerPage,
					dropIn:			obj.dropIn,
					dom:			dom,
					data:			obj.data,
					pagingPrefix:	obj.pagingPrefix
				});
			});
		}else{
			$(obj.pagingPrefix+'Previous').unbind('click').hide();
		}
		
		$(obj.dropIn,dom).html(htmlStr);
		
		return window.shrimp7;
	},
	buildTweet:function(data,i){
		var	message,
			userLink = data.user.name+' ',
			tweetCopyToFacebookButton,
			tweetCopyToFriendfeedButton,
			tweetRemoveButton = this.setupParams.tweet.remove,
			tweetReplyButton="",
			tweetCompressed="",
			tweetUserFilter="",
			cssClass='tweet',
			htmlStr=this.setupParams.tweet.entry,
			replaceWith,
			reg;
		
		if(data.user.following){
			userLink = '<a href="javascript:shrimp7.twitter.followers.openFollower(\''+data.user.id+'\')" title="Direct tweet">'+data.user.name+'</a> ';
		}
		
		if(setting("twitterUserId")==data.user.id||setting("twitterUsername")==data.user.screenName){
			
		}else{
			tweetRemoveButton = '';
			tweetUserFilter = this.setupParams.tweet.userFilter;
			tweetReplyButton = this.setupParams.tweet.reply;
		}
		if(setting("boolFacebook")){
			tweetCopyToFacebookButton = this.setupParams.tweet.copyToFacebookButton;
		}else{
			tweetCopyToFacebookButton = "";
		}
		
		/*
		* Remote copy2facebook method..
		*
		* Just send an tweet to Twitter with for example at the end the following code: c2fb
		* and shrimp7 will try to copy that message to Facebook.
		*
		* Known problems: when the gadget will be reinstalled, the gadget tries to send all
		* the c2fb messages again..
		*
		* When the gadget crashed (debugger) and new messages are comming in a c2fb message
		* could end up on page 2 after the debugger has closed.. then the c2fb message will
		* be only copied when a user visit page 2..
		*/
		
		//shrimp7.twitter.findC2codes('Facebook',data,i);
		//shrimp7.twitter.findC2codes('Friendfeed',data,i);
		//shrimp7.twitter.findC2codes('All',data,i);
		
		if(data.message.match('@'+setting("twitterScreenName"))!==NULL){
			cssClass='tweetReply';
		}
		
		if(setting("twitterSpyUsers").match(data.user.screen_name)!==NULL){
			cssClass='tweetSpy';
		}
		
		message = parseLinks(data.message);
		
		message = emoticons(message);
		
		replaceWith = {
			i:i,
			dataId:data.id,
			dataUserId:data.user.id,
			dataUserScreenname:data.user.screenName,
			dataUserProfileImgUrl:data.user.profileImgUrl,
			dataPostTime:relativeTime(data.postTime,'timestamp'),
			dataMessage:message,
			cssClass:cssClass,
			tweetCompressed:tweetCompressed,
			userLink:userLink
		};
		
		for(key in replaceWith){
			reg = new RegExp('\{{1}'+key+'\}{1}','igm');
			tweetRemoveButton = tweetRemoveButton.replace(reg,replaceWith[key]);
			tweetReplyButton = tweetReplyButton.replace(reg,replaceWith[key]);
			tweetUserFilter = tweetUserFilter.replace(reg,replaceWith[key]);
			tweetCopyToFacebookButton = tweetCopyToFacebookButton.replace(reg,replaceWith[key]);
			htmlStr = htmlStr.replace(reg,replaceWith[key]);
		}
		
		htmlStr = htmlStr.replace('{tweetRemoveButton}',tweetRemoveButton);
		htmlStr = htmlStr.replace('{tweetReplyButton}',tweetReplyButton);
		htmlStr = htmlStr.replace('{tweetUserFilter}',tweetUserFilter);
		htmlStr = htmlStr.replace('{tweetCopyToFacebookButton}',tweetCopyToFacebookButton);
		
		return htmlStr;
	},
	spyUserList:function(obj){
		if(setting("twitterSpyUsers")!==""){
			var	spyUsersArr = readSpyUsers(),
				i,
				twitUpdatesPerHourTemp = this.calculateRefreshes(),
				replaceWith,
				htmlStr = this.setupParams.spyUser;
			
			$(obj.dropIn).html("");
			for(i=0;i<spyUsersArr.length;i++){
				var spyUser = spyUsersArr[i].split("(");
				
				replaceWith = {
					i:i,
					dataUserName:spyUser[0],
					dataValue:spyUser[1]
				};
				
				for(key in replaceWith){
					reg = new RegExp('\{{1}'+key+'\}{1}','igm');
					htmlStr = htmlStr.replace(reg,replaceWith[key]);
				}
				
				$(obj.dropIn).append(htmlStr);
				
				$("#slider"+spyUser[0]).slider({
					value:spyUser[1],
					min:1,
					max:10,
					step:1,
					start:function(event,ui){
						twitUpdatesPerHourTemp = twitUpdatesPerHourTemp-parseInt(ui.value,10);
					},
					slide:function(event,ui){
						$("#"+this.id+"value").html(ui.value);
						var ff = twitUpdatesPerHourTemp;
						$(".twitterUpdateCounter").html(ff+parseInt(ui.value,10));
					},
					stop:function(event,ui){
						twitUpdatesPerHourTemp = twitUpdatesPerHourTemp+parseInt(ui.value,10);
						$(".twitterUpdateCounter").html(twitUpdatesPerHourTemp);
					}
				});
			}
			
			$(".twitterUpdateCounter").html(twitUpdatesPerHourTemp);
		}else{
			$(obj.dropIn).html("No users in your spy list");
		}
		return window.shrimp7;
	},
	getReceivedDirectMessages:function(callback){
		this.con.getReceivedDirectMessages(callback);
		return window.shrimp7;
	},
	readSpyUsers:function(){
		if(setting("twitterSpyUsers")!==""){
			var	spyUsers = setting("twitterSpyUsers"),
				spyUsersArr = spyUsers.split(","),
				i;
			
			for(i=0;i<spyUsersArr.length;i++){
				var spyUser = spyUsersArr[i].split("("),
					screenname = spyUser[0];
				
				this.data.spy.users[screenname] = spyUser[1];
			}
			
			return spyUsersArr;
		}else{
			return FALSE;
		}
		return window.shrimp7;
	},
	fetchSpyUsers:function(data){
		if(!data){
			var	spyUsersArr = this.readSpyUsers(),
				i;
			
			for(i=0;i<spyUsersArr.length;i++){
				var spyUser = spyUsersArr[i].split("("),
					thisscreenname = spyUser[0],
					screennameRefresh = spyUser[1];
					
				this.data.spy.data[thisscreenname] = {refresh:screennameRefresh};
				
				this.con.userTimeline({
					screenname:thisscreenname,
					success:function(){
						
					}
				});
			}
		}else{
			this.con.userTimeline({
				screenname:data,
				success:function(){
					
				}
			});
		}
		return window.shrimp7;
	},
	fetchSavedSearches:function(obj){
		// data === FALSE every first session of shrimp7, so after computer restart etc..
		if(obj.refresh){
			var i,ssc=this.data.savedSearches;
			this.con.savedSearches(function(data){
				var setStandardValues=function(data){
					for(i=0;i<data.length;i++){
						ssc[i].refreshTime = 2;
						ssc[i].autoFollow = 0;
					}
				};
				if(data!==errorTxt){
					ssc = shrimp7.twitter.data.savedSearches = data;
					
					if(setting("twitterSavedSearches")!==""){
						var savedSearches = setting("twitterSavedSearches").split(","),i,values;
						// When the Twitter saved searches is the same as shrimp7 saved searches
						if(savedSearches.length===data.length){
							for(i=0;i<savedSearches.length;i++){
								values = savedSearches[i].split("(");
								shrimp7.twitter.data.savedSearches[i].refreshTime = values[1];
								shrimp7.twitter.data.savedSearches[i].autoFollow = values[2];
							}
						}
						// When there is difference between the Twitter server saved searches and shrimp7
						// shrimp7 saved searches then set standard values for refreshTime and autoFollow
						else{
							setStandardValues(data);
						}
					}else{
						setStandardValues(data);
					}
					
					// Now walk the savedSearchesCache list and set the timer for each query
					for(i=0;i<ssc.length;i++){
						var	ff = ssc[i].id,
							searchData = ssc[i],
							autoFollow = FALSE;
							
						clearTimeout(shrimp7.twitter.timer.search[ff]);
						if(parseInt(searchData.autoFollow)===1){
							autoFollow = TRUE;
						}
						shrimp7.twitter.search({
							query:		ssc[i].query,
							cache:		FALSE,
							autoFollow:	autoFollow
						});
						shrimp7.twitter.timer.search[ff] = setTimeout(function(){
													fetchSavedSearches({refresh:false,data:searchData});
												},3600000/ssc[i].refreshTime);
					}
					
					if(obj.success!==undefined){
						obj.success();
					}
					
					// Save everything
					shrimp7.twitter.saveSearchSettings();
				}
			});
		}else if(obj.data!==UNDEFINED){
			var autoFollow = FALSE;
			
			if(parseInt(obj.data.autoFollow)===1){
				autoFollow = TRUE;
			}
			
			clearTimeout(shrimp7.twitter.timer.search[obj.data.id]);
			
			this.search({
				query:obj.data.query,
				cache:FALSE,
				autoFollow: autoFollow
			});
			
			shrimp7.twitter.timer.search[obj.data.id] = setTimeout(function(){twitterFetchSavedSearches({refresh:false,data:data});},3600000/obj.data.refreshTime);
		}
		return window.shrimp7;
	},
	calculateRefreshes:function(callback){
		var total = shrimp7.twitter.updatesPerHour,i;
		if(setting("twitterSpyUsers")!==""){
			var	spyUsersArr = readSpyUsers();
			
			for(i=0;i<spyUsersArr.length;i++){
				var spyUser = spyUsersArr[i].split("(");
				
				total = total+parseInt(spyUser[1],10);
			}
		}
		
		if(this.data.savedSearches.length>0){
			for(i=0;i<this.data.savedSearches.length;i++){
				total = total+parseInt(this.data.savedSearches[i].refreshTime,10);
			}
		}
		
		callback(total);
		return window.shrimp7;
	},
	normalizer:function(data,callback){
		if(data[0]!==UNDEFINED){
			var	i,
				normalized=[],
				timeValue;
			
			for(i=0;i<data.length;i++){
				timeValue = Date.parse(data[i].created_at)/1000;
				
				normalized[i] = {
					id:				data[i].id,
					postTime:		timeValue,
					user:			{
						id:				data[i].user.id,
						name:			data[i].user.name,
						screenName:		data[i].user.screen_name,
						profileImgUrl:	data[i].user.profile_image_url
					},
					following:		data[i].following,
					message:		data[i].text
				};
			}
		}
		callback(normalized);
		return window.shrimp7;
	},
	search:function(obj){
		if(obj.beforeSearch!==UNDEFINED){
			obj.beforeSearch();
		}
		
		if(obj.query!==UNDEFINED){
			this.con.search(obj.query,function(data){
				if(data!==errorTxt&&obj.success!==UNDEFINED){
					obj.success(data);
				}else if(obj.error!==UNDEFINED){
					obj.error();
				}
			});
		}
	},
	saveSearchSettings:function(){
		var saveStr = [],refreshTime,autoFollow,i,ssc=this.data.savedSearches;
		for(i=0;i<ssc.length;i++){
			if($("#slider"+ssc[i].id+"value").length===0){
				refreshTime = 2;
			}else{
				refreshTime = $("#slider"+ssc[i].id+"value").html();
			}
			if($("#autofollow"+ssc[i].id).is(":checked")){
				autoFollow = 1;
			}else{
				autoFollow = 0;
			}
			this.data.savedSearches[i].refreshTime = refreshTime;
			this.data.savedSearches[i].autoFollow = autoFollow;
			saveStr.push(this.data.savedSearches[i].id+'('+refreshTime+'('+autoFollow);
		}
		setting("twitterSavedSearches",saveStr.join(","));
		return window.shrimp7;
	},
	deleteTweet:function(obj){
		if(obj.beforeDelete!==UNDEFINED){
			obj.beforeDelete();
		}
		
		if(obj.id!==UNDEFINED){
			this.con.deleteTweet(obj.id,function(data){
			if(data!==errorTxt&&obj.success!==UNDEFINED){
					obj.success(data);
				}else if(obj.error!==UNDEFINED){
					obj.error();
				}
			});
		}
		if(obj.returnSelf!==false){
			return window.shrimp7;
		}
	}
};

/*
* Twitter connector functions
*/

shrimp7.twitter.con = {
	shrimp7URL:soepgarnaalURL+'shrimp7/',
	requestToken:function(callback){
		$.ajax({
			type:"GET",
			url:this.shrimp7URL+"oauth/request_token.php",
			dataType:"html",
			success:function(data){
				var	parts = data.split("&"),
					partsData = [];
				jQuery.each(parts,function(i){
					partsData[i] = this.split("=");
				});
				setting("twitterOauthToken",partsData[0][1]);
				setting("twitterOauthTokenSecret",partsData[1][1]);
				callback(twitterURL+'oauth/authorize?oauth_token='+setting("twitterOauthToken"));
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	requestAccessToken:function(callback){
		$.ajax({
			type:"GET",
			url:this.shrimp7URL+"oauth/access_token.php?oauth_token="+setting("twitterOauthToken")+"&oauth_token_secret="+setting("twitterOauthTokenSecret")+"&oauth_verifier="+setting("twitterPIN"),
			dataType:"html",
			success:function(data){
				if(data!=""){
					var	parts=data.split("&"),
						partsData=[];
					jQuery.each(parts,function(i){
						partsData[i]=this.split("=");
					});
					setting("twitterOauthTokenAccess",partsData[0][1]);
					setting("twitterOauthTokenSecretAccess",partsData[1][1]);
					setting("twitterUserId",partsData[2][1]);
					setting("twitterScreenName",partsData[3][1]);
					callback('ok');
				}else{
					callback(errorTxt);
				}
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	signature:function(url,params,callback){
		$.ajax({
			type:"GET",
			url:this.shrimp7URL+"oauth/sign_request.php?endpoint="+encodeURI(url)+"&oauth_token="+setting("twitterOauthTokenAccess")+"&oauth_token_secret="+setting("twitterOauthTokenSecretAccess")+params,
			dataType:"text",
			success:function(data){
				callback(data);
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	postWithSig:function(url,params,callback){
		$.ajax({
			type:"GET",
			url:this.shrimp7URL+"oauth/twitterPost.php?endpoint="+encodeURI(url)+"&oauth_token="+setting("twitterOauthTokenAccess")+"&oauth_token_secret="+setting("twitterOauthTokenSecretAccess")+params,
			dataType:"json",
			success:function(data){
				callback(data);
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	ajaxCall:function(callback,url,data){
		if(config.system===web){
			$.jsonp({
				url:url,
				data:data,
				cache:TRUE,
				timeout:20000,
				success:function(json){
					callback(json);
				},
				error:function(){
					callback(errorTxt);
				}
			});
		}else{
			$.ajax({
				type:"GET",
				cache:TRUE,
				url:url,
				data:data,
				dataType:'json',
				success:function(data){
					executeFunctionByName(callbackObj.func,window,data);
				},
				error:function(XMLHttpRequest,textStatus,errorThrown){
					executeFunctionByName(callbackObj.func,window,errorTxt);
				}
			});
		}
		return window.shrimp7;
	},
	getUserInfo:function(id,dom,callback){
		var sendData = ['type=GET','user_id='+setting("twitterUserId")],
			url = twitterURL+'users/show.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	userTimeline:function(obj){
		var sendData = ['type=GET','screen_name='+obj.screenname],
			url = twitterURL+'statuses/user_timeline.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(obj,url,data);
			}else{
				obj.error(errorTxt);
			}
		});
		return window.shrimp7;
	},
	friendsTimeline:function(obj){
		var sendData = ['type=GET','user_id='+setting("twitterUserId")],
			url = twitterURL+'statuses/friends_timeline.json';
		
		if(obj.limit!==UNDEFINED){
			sendData.push('count='+obj.limit);
		}
		if(obj.page!==UNDEFINED){
			sendData.push('page='+obj.page);
		}
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(obj.callback,url,data);
			}else{
				obj.callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	savedSearches:function(callback){
		var sendData = ['type=GET'],
			url = twitterURL+'saved_searches.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	repliesTimeline:function(limit,page,callback){
		var sendData = ['type=GET','count='+limit,'page='+page],
			url = twitterURL+'statuses/mentions.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	getRateLimit:function(callback){
		var sendData = ['type=GET'],
			url = twitterURL+'account/rate_limit_status.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	getReceivedDirectMessages:function(callback){
		var sendData = ['type=GET'],
			url = twitterURL+'direct_messages.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	getFollowersInfo:function(id,dom,callback){
		var sendData = ['type=GET','user_id='+setting("twitterUserId")],apiurl="";
		
		if(id!==NULL){
			apiurl='/'+id;
		}
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(twitterURL+'statuses/followers'+apiurl+'.json','&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,twitterURL+'statuses/followers'+apiurl+'.json',data);
			}else{
				callback(errorTxt);
			}
		});
		
		return window.shrimp7;
	},
	newTweet:function(obj){
		var sendData = ['type=POST','status=' + encodeURIComponent(obj.tweet)],
			url = twitterURL+'statuses/update.json';
		
		if(obj.inReplyTo!==UNDEFINED){
			sendData.push('in_reply_to_status_id=' + obj.inReplyTo);
		}
		
		if(config.system===web){
			this.postWithSig(url,'&' + sendData.join("&"),function(data){
				obj.success(data);
			});
		}else{
			this.signature(url,'&'+sendData.join("&"),function(postData){
				if(postData!==errorTxt){
					$.ajax({
						type:"POST",
						url:url,
						dataType:"text",
						data:postData,
						success:function(data){
							obj.success(data);
						},
						error:function(XMLHttpRequest,textStatus,errorThrown){
							obj.error(errorTxt);
						}
					});
				}else{
					obj.callback(errorTxt);
				}
			});
		}
		return window.shrimp7;
	},
	directTweet:function(userId,tweet,callback){
		var sendData = ['type=POST','user_id='+userId,'text='+tweet],
			url = twitterURL+'direct_messages/new.json';
		
		this.signature(url,'&'+sendData.join("&"),function(postData){
			if(postData!==errorTxt){
				$.ajax({
					type:"POST",
					url:url,
					dataType:"json",
					data:postData,
					success:function(data){
						callback(data);
					},
					error:function(XMLHttpRequest,textStatus,errorThrown){
						callback(errorTxt);
					}
				});
			}else{
				callback(errorTxt);
			}
		});
		return window.shrimp7;
	},
	createFriend:function(id,callback){
		var sendData = ['type=POST','follow=true'],
			url = twitterURL+'friendships/create/'+id+'.json';
		
		if(config.system===web){
			this.postWithSig(url,'&'+sendData.join("&"),function(data){
				try{
					callback(data);
				}catch(err){
					
				}
			});
		}else{
			this.signature(url,'&'+sendData.join("&"),function(postData){
				if(postData!==errorTxt){
					$.ajax({
						type:"POST",
						url:url,
						dataType:"json",
						data:postData,
						success:function(data){
							callback(data);
						},
						error:function(XMLHttpRequest,textStatus,errorThrown){
							callback(errorTxt);
						}
					});
				}else{
					callback(errorTxt);
				}
			});
		}
		return window.shrimp7;
	},
	search:function(query,callback){
		var sendData = ['type=GET','q='+encodeURIComponent(query),'rpp=100'],
			url = 'http://search.twitter.com/search.json';
		
		if(config.system===web){
			sendData.push('callback=C');
		}
		
		this.signature(url,'&'+sendData.join("&"),function(data){
			if(data!==errorTxt){
				shrimp7.twitter.con.ajaxCall(callback,url,data);
			}else{
				callback(errorTxt);
			}
		});
	},
	deleteTweet:function(tweetId,callback){
		var sendData = ['type=POST'],
			url = twitterURL+'statuses/destroy/'+tweetId+'.json';
		
		if(config.system===web){
			this.postWithSig(url,'&'+sendData.join("&"),function(data){
				callback(data);
			});
		}else{
			this.signature(url,'&'+sendData.join("&"),function(postData){
				if(postData!==errorTxt){
					$.ajax({
						type:"POST",
						url:url,
						dataType:"json",
						data:postData,
						success:function(data){
							callback(data);
						},
						error:function(XMLHttpRequest,textStatus,errorThrown){
							callback(errorTxt);
						}
					});
				}else{
					callback(errorTxt);
				}
			});
		}
		return window.shrimp7;
	}
};

